package com.fhao.trans.controller;

import com.fhao.trans.service.LogService;
import com.fhao.trans.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 事务的传播机制
 */
@RequestMapping("/user2")
@RestController
public class UserController2 {
    @Autowired
    private UserService userService;
    @Autowired
    private LogService logService;
    @Transactional
    @RequestMapping("/register")
    public boolean register(String userName,String password) {
        /**
         * 用户表的插入和日志表的插入,理应在Service完成
         * 为了方便教学,就放在Controlelr里面完成.
         * userService和logService 中的事务传播机制为 @Transactional(propagation = Propagation.REQUIRED)
         * 验证该传播机制: 如果其中一个失败,则所有事务回滚. 如果成功则都成功.
         *
         * propagation = Propagation.NESTED 与 REQUIRED的区别就是 NESTED可以部分回滚(手动回滚), REQUIRED要么都回滚要么都提交.
         * 其余情况都一样
         */
        //插入用户表
        Integer result = userService.insert(userName, password);
        System.out.println("插入用户表,result: "+result);
//        插入日志表
        Integer logResult = logService.insert(userName,"用户注册");
        System.out.println("插入日志表,result: "+ logResult);
        return true;
    }
}














